package com.dbapp.garden.controller.student;

import com.dbapp.garden.common.DataTableUtils;
import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.entity.GardenStaffInfo;
import com.dbapp.garden.entity.GardenStudentAssign;
import com.dbapp.garden.entity.GardenStudentInfo;
import com.dbapp.garden.service.GardenStaffInfoService;
import com.dbapp.garden.service.GardenStudentAssignService;
import com.dbapp.garden.service.GardenStudentInfoService;
import com.dbapp.garden.vm.StudentAssignVm;
import com.dbapp.garden.vo.GardenStudentAssignVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author gangzi
 */
@Controller
public class StudentAssignController {

    @Autowired
    private GardenStaffInfoService staffInfoService;

    @Autowired
    private GardenStudentInfoService studentInfoService;

    @Autowired
    private GardenStudentAssignService assignService;

    @GetMapping("/assignment")
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_ASSIGN')")
    public String toStudentAssignPage(HttpServletRequest request, Model model) {

        Map<String, Object> query = new HashMap<>(16);
        query.put("isTeacher", 1);
        List<GardenStaffInfo> teachers = staffInfoService.getStaffList(query);
        query.clear();
        query.put("isAdviser", 1);
        List<GardenStaffInfo> advisers = staffInfoService.getStaffList(query);

        model.addAttribute("teachers", teachers);
        model.addAttribute("advisers", advisers);
        return "student/studentassignment";
    }


    @PostMapping("/studentassign")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_ASSIGN')")
    @Transactional(rollbackFor = Exception.class)
    public Map<String, ?> assignStudent(HttpServletRequest request, @RequestBody @Valid StudentAssignVm assignVm) {
        String[] stuIds = StringUtils.split(assignVm.getStuId(), ",");

        Arrays.stream(stuIds).forEach(id -> {
            if (StringUtils.isNotEmpty(id)) {
                Integer stuId = Integer.parseInt(id);
                GardenStudentInfo studentInfo = studentInfoService.findById(stuId);

                GardenStudentAssign assign = new GardenStudentAssign();
                assign.setCreateTime(new Date());
                assign.setUpdateTime(new Date());
                //分配前的顾问
                assign.setBeforeAssignTeacher(studentInfo.getStuAffiliatedAdviser());

                //分配后的顾问
                assign.setAfterAssignTeacher(assignVm.getAdviser());
                assign.setStudentId(stuId);
                assignService.save(assign);
                studentInfo.setStuLastAssign(assign.getId());
                studentInfo.setStuAffiliatedAdviser(assignVm.getAdviser());
                studentInfo.setStuAssignCount(studentInfo.getStuAssignCount() + 1);
                studentInfo.setStuAssignDate(new Date());
                studentInfoService.save(studentInfo);
            }


        });


        return RenderJSON.makeStandMap(1, "恭喜您，分配成功！", "ok");
    }

    @GetMapping("/assignhistory/{id}")
    public String toHistoryAssignPage(HttpServletRequest request, @PathVariable("id") Integer id, Model model) {
        GardenStudentInfo studentInfo = studentInfoService.findById(id);
        model.addAttribute("student", studentInfo);
        return "student/assignhistory";
    }

    @PostMapping("/assignhistorylist")
    @ResponseBody
//    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO')")
    public Map<String, ?> assignHistoryList(HttpServletRequest request, String param, Integer stuId) {


        Map<String, Object> paramMap = DataTableUtils.parseParam(param);
        if (paramMap == null) {
            return RenderJSON.makeMap(-1, "参数不合法！", null, "");
        }
        String sEcho = (String) paramMap.get("sEcho");
        String sSearch = (String) paramMap.get("sSearch");
        int iDisplayStart = (int) paramMap.get("iDisplayStart");
        int iDisplayLength = (int) paramMap.get("iDisplayLength");
        paramMap.clear();
        paramMap.put("search", sSearch);
        if (stuId != null) {
            paramMap.put("studentId", stuId);
        }
        paramMap.put("start", iDisplayStart);
        paramMap.put("limit", iDisplayLength > 0 ? iDisplayLength : Integer.MAX_VALUE);


        List<GardenStudentAssign> studentList = assignService.getStudentAssignList(paramMap);

        List<GardenStudentAssignVo> studentAssignVoList = studentList.stream().map(a -> {
            GardenStudentAssignVo assignVo = new GardenStudentAssignVo();
            assignVo.setId(a.getId());
            assignVo.setCreateTime(a.getCreateTime());
            assignVo.setBeforeAssignTeacher(getStaffRealName(a.getBeforeAssignTeacher()));
            assignVo.setAfterAssignTeacher(getStaffRealName(a.getAfterAssignTeacher()));
            assignVo.setAssignOperator("刚子");
            assignVo.setStudentId(a.getStudentId());
            assignVo.setStudentName(studentInfoService.findById(a.getStudentId()).getStuName());

            return assignVo;
        }).collect(Collectors.toList());

        Integer count = assignService.getStudentAssignCount(paramMap);

        return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, studentAssignVoList, "");
    }

    /**
     * 根据传入的逗号分割的过个用户ID获取转换后的用户名
     *
     * @param userIds
     * @return
     */
    private String getStaffRealName(String userIds) {

        if (StringUtils.isEmpty(userIds)) {
            return "";
        }

        List<GardenStaffInfo> staffInfoList = new ArrayList<>();
        Arrays.stream(userIds.split(",")).forEach(sId -> {
            if (StringUtils.isNotEmpty(sId)) {
                Integer staffId = Integer.parseInt(sId);
                GardenStaffInfo staffInfo = staffInfoService.findById(staffId);
                if (staffInfo != null) {
                    staffInfoList.add(staffInfo);
                }

            }

        });


//        Stream.of(userIds.split(",")).filter(s->StringUtils.isNotEmpty(s)).map(s->Integer.valueOf(s)).collect(Collectors.toList());

        return staffInfoList.stream().map(s -> s.getStaffRealName()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
    }
}
